package cn.ges.movie.config.websecurity

import cn.ges.base.sta.constant.StaBaseConstant
import cn.ges.movie.filter.JwtAuthenticationFilter
import com.ges.common.config.jwt.UserSigningKeyResolver
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpMethod
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.builders.WebSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.config.http.SessionCreationPolicy
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
import javax.annotation.Resource

/**
 * spring security 配置
 * EnableGlobalMethodSecurity:开启权限注解支持
 * prePostEnabled 开启@PreAuthorize,@PostAuthorize支持
 * @author gespent@163.com
 * @date 2020-07-14 17:20:49
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
//@AutoConfigureAfter(JwtAuthAutoConfiguration::class)
open class WebSecurityConfig() : WebSecurityConfigurerAdapter() {

    @Resource
    lateinit var userSigningKeyResolver: UserSigningKeyResolver

    /**
     * 设置 HTTP 验证规则 有先后顺序
     */
    @Throws(Exception::class)
    override fun configure(http: HttpSecurity) {
        // 关闭csrf验证
        http.csrf().disable()
            // Spring Security永远不会创建HttpSession，它不会使用HttpSession来获取SecurityContext
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            // 对请求进行认证
            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
            // 放行所有授权接口
            .antMatchers("/**/auth/**").permitAll()
            .antMatchers("/v2/auth/menu/").permitAll()
            // 电影管理接口
            .antMatchers("/v1/admin/**").hasAnyAuthority("ALL", "BG_ADMIN")
            // 其余请求需要身份User,允许用户访问其他路径
            .anyRequest().hasAnyAuthority(StaBaseConstant.BG_USER_AUTH, "ALL", "BG_ADMIN")
            .and()
            .addFilterBefore(
                JwtAuthenticationFilter(userSigningKeyResolver),
                UsernamePasswordAuthenticationFilter::class.java
            )
    }

    /**
     * 在这里配置security放行的请求
     */
    override fun configure(web: WebSecurity) {
        // Error提示
        web.ignoring().antMatchers("/error/**")
    }

    @Throws(Exception::class)
    override fun configure(auth: AuthenticationManagerBuilder?) {
    }
}